import 'package:flutter/material.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';

class CoordinateUtils {
  CoordinateUtils(
      {this.color = Colors.grey, this.strokeWidth = 1.0, required this.size});

  final Color color;
  final double strokeWidth;

  final Size size;
  final Paint paint = Paint();

  /// 绘制方法
  void paintCoordinate({
    required int hLineNum,
    required int vLineNum,
    required Canvas canvas,
    int gapNum = 1,
  }) {
    /// 绘制坐标轴
    drawLine(
        lineNum: hLineNum,
        axis: Axis.horizontal,
        canvas: canvas,
        size: size,
        gapNum: gapNum);
    drawLine(
        lineNum: vLineNum,
        axis: Axis.vertical,
        canvas: canvas,
        size: size,
        gapNum: gapNum);
  }

  void drawLine(
      {required Canvas canvas,
      required int lineNum,
      Axis axis = Axis.horizontal,
      int gapNum = 1,
      required Size size}) {
    canvas.save();
    canvas.scale(1, -1);
    paint
      ..color = Colors.grey
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;
    double step =
        axis == Axis.vertical ? size.height / lineNum : size.width / lineNum;

    for (var i = 0; i < lineNum + 1; i++) {
      if (i == 0) {
        paint.color = color;
        paint.strokeWidth = strokeWidth;
      } else {
        paint.color = Colors.grey;
        paint.strokeWidth = 1.0;
      }
      if (axis == Axis.horizontal) {
        /// 横向
        canvas.drawLine(const Offset(0.0, 0.0), Offset(size.width, 0.0), paint);
      } else {
        /// 纵向
        canvas.drawLine(
            const Offset(0.0, 0.0), Offset(0.0, size.height), paint);
      }
      TextAlign align =
          axis == Axis.vertical ? TextAlign.start : TextAlign.left;
      Offset textOffset = axis == Axis.vertical
          ? const Offset(0.0, 4.0)
          : const Offset(-4.0, 0.0);
      String text = axis == Axis.vertical ? "${i * gapNum}" : "${i * gapNum}";

      /// 删除一个0
      if ((axis == Axis.horizontal && i != 0) || axis == Axis.vertical) {
        if (i == 0) {
          textOffset = const Offset(-4.0, 0.0);
        }

        CanvasUtils.drawText(
          canvas: canvas,
          textAlign: align,
          textOffset: textOffset,
          paint: paint,
          fontWeight: FontWeight.normal,
          fontSize: 10,
          text: text,
        );
      }

      Offset offset =
          axis == Axis.horizontal ? Offset(0.0, step) : Offset(step, 0.0);
      canvas.translate(offset.dx, offset.dy);
    }
    canvas.restore();
  }
}
